function [ a ] = fcn3lsfit( x, f, phi1, phi2, phi3 ) %#codegen
%FCN3LSFIT 用a(1)*phi1+a(2)*phi2+a(3)*phi3最小二乘拟合x点集上给出的f函数值
%
% Input Arguments:
% x: 向量，自变量
% f: 向量，被拟合的函数值
% phi1, phi2, phi3: 拟合函数句柄
%
% Output Arguments:
% a: 长度为3的列向量
%
% References:
% [1] 李庆扬, 关治, 白峰杉. 数值计算原理. 北京: 清华大学出版社, 2000: 2-2节

% 计算法方程
A = zeros(3); % 法方程系数矩阵
b = zeros(3, 1); % 法方程常数值向量
for i=1:length(x)
    A(1, 1) = A(1, 1) + phi1(x(i)) * phi1(x(i));
    A(1, 2) = A(1, 2) + phi1(x(i)) * phi2(x(i));
    A(1, 3) = A(1, 3) + phi1(x(i)) * phi3(x(i));
    
    A(2, 1) = A(2, 1) + phi2(x(i)) * phi1(x(i));
    A(2, 2) = A(2, 2) + phi2(x(i)) * phi2(x(i));
    A(2, 3) = A(2, 3) + phi2(x(i)) * phi3(x(i));
    
    A(3, 1) = A(3, 1) + phi3(x(i)) * phi1(x(i));
    A(3, 2) = A(3, 2) + phi3(x(i)) * phi2(x(i));
    A(3, 3) = A(3, 3) + phi3(x(i)) * phi3(x(i));
    
    b(1, 1) = b(1, 1) + f(i) * phi1(x(i));
    b(2, 1) = b(2, 1) + f(i) * phi2(x(i));
    b(3, 1) = b(3, 1) + f(i) * phi3(x(i));
end
a = A \ b;
end